﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace FileCache
{
    public class Cache
    {
        private static Queue<Cache_Obj> queCache = new Queue<Cache_Obj>();
        private static Dictionary<string, Cache_Obj> dicCache = new Dictionary<string, Cache_Obj>();

        static Cache()
        {
            Thread thread = new Thread(DO);
            thread.Priority = ThreadPriority.Lowest;
            thread.Start();
        }

        public static void Add(string key, string value)
        {
            Cache_Obj c = new Cache_Obj();
            c.Key = key;
            c.Value = value;
            if (!dicCache.Keys.Contains(c.Key))
            {
                var temp = new Cache_Obj();
                temp.Key = key;
                temp.Value = value;
                dicCache.Add(c.Key, temp);
            }
            queCache.Enqueue(c);
        }

        public static void Add<T>(string key, T value)
        {
            Cache_Obj c = new Cache_Obj();
            c.Key = key;
            c.Value = value;
            if (!dicCache.Keys.Contains(c.Key))
            {
                var temp = new Cache_Obj();
                temp.Key = key;
                temp.Value = value;
                dicCache.Add(c.Key, temp);
            }
            queCache.Enqueue(c);
        }

        public static string Get(string key)
        {
            if (dicCache.Keys.Contains(key) && dicCache[key].Value!=null)
            {
                return (string)dicCache[key].Value;
            }
            string keyMd5 = MD5Hash.getMd5Hash(key);
            string path = CreatePath(keyMd5);
            if (File.Exists(path))
            {
                return File.ReadAllText(path, System.Text.Encoding.GetEncoding("gb2312"));
            }
            else
            {
                return default(string);
            }
        }

        public static T Get<T>(string key)
        {
            if (dicCache.Keys.Contains(key) && dicCache[key].Value != null)
            {
                return (T)dicCache[key].Value;
            }
            string str = Get(key);
            if (string.IsNullOrEmpty(str))
            {
                return default(T);
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }

        private static void DO()
        {
            while (true)
            {

                while (queCache.Count > 0)
                {
                    var c = queCache.Dequeue();
                    if (c.Value == null || string.IsNullOrEmpty(c.Key))
                    {
                        continue;
                    }
                    c.Key_MD5 = MD5Hash.getMd5Hash(c.Key);
                    if (c.Value.GetType() == typeof(string))
                    {
                        c.Value_MD5 = MD5Hash.getMd5Hash((string)c.Value);
                    }
                    else if (c.Value.GetType() == typeof(byte[]))
                    {
                        c.Value_MD5 = MD5Hash.getMd5Hash((byte[])c.Value);
                    }
                    else
                    {
                        var str = Newtonsoft.Json.JsonConvert.SerializeObject(c.Value);
                        c.Value = str;
                        c.Value_MD5 = MD5Hash.getMd5Hash(str);
                    }
                    Dealwith(ref c);
                }
                Thread.Sleep(5000);
            }
        }

        private static void Dealwith(ref Cache_Obj c)
        {
            if (!dicCache.Keys.Contains(c.Key))
            {
                Cache_Obj t = new Cache_Obj();
                t.Key = c.Key;
                t.Key_MD5 = "";
                dicCache.Add(c.Key, t);
            }
            var temp = dicCache[c.Key];
            if (temp.Value_MD5 == c.Value_MD5)
            {
                return;
            }
            else
            {
                string filePath = CreatePath(c.Key_MD5);
                if (File.Exists(filePath))
                {
                    byte[] value = File.ReadAllBytes(filePath);
                    var md5new = MD5Hash.getMd5Hash(value);
                    if (c.Value_MD5 != md5new)
                    {
                        if (c.Value.GetType() == typeof(string))
                        {
                            value = System.Text.Encoding.GetEncoding("gb2312").GetBytes((string)c.Value);
                        }
                        else if (c.Value.GetType() == typeof(byte[]))
                        {
                            value = (byte[])c.Value;
                        }
                        File.WriteAllBytes(filePath, value);
                    }
                }
                else
                {
                    FileStream sw = null;
                    try
                    {
                        FileInfo file = new FileInfo(filePath);
                        if (!file.Directory.Exists)
                        {
                            file.Directory.Create();
                        }
                        sw = file.Create();
                        byte[] value = null;
                        if (c.Value.GetType() == typeof(string))
                        {
                            value = System.Text.Encoding.GetEncoding("gb2312").GetBytes((string)c.Value);
                        }
                        else if (c.Value.GetType() == typeof(byte[]))
                        {
                            value = (byte[])c.Value;
                        }
                        sw.Write(value, 0, value.Length);
                        sw.Flush();

                    }
                    finally
                    {
                        if (sw != null)
                        {
                            try
                            {
                                sw.Close();
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            if (c.Value.GetType() == typeof(byte[]))
            {
                c.Value_MD5 = MD5Hash.getMd5Hash((byte[])c.Value);
            }
            else
            {
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(c.Value);
                c.Value = str;
                c.Value_MD5 = MD5Hash.getMd5Hash(str);
            }
            c.Value = null;
            dicCache[c.Key] = c;
        }


        private static string CreatePath(string keyMd5)
        {
            string p1 = keyMd5.Substring(0, 1);
            string p2 = keyMd5.Substring(0, 2);
            string path = CachePath + "/" + p1 + "/" + p2 + "/" + keyMd5;
            return path;
        }


        private static string CachePath
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["FileCache"];
            }
        }


    }

    internal class Cache_Obj
    {
        public string Key
        {
            get;
            set;
        }

        public string Key_MD5
        {
            get;
            set;
        }

        public object Value
        {
            get;
            set;
        }

        public string Value_MD5
        {
            get;
            set;
        }
    }
}
